/**
 * 统一API响应类型定义
 * 基于后端 app/core/response.py 的响应格式
 */

// 错误类型枚举 - 与后端 ErrorTypes 保持一致
export enum ErrorType {
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR',
  PERMISSION_ERROR = 'PERMISSION_ERROR',
  NOT_FOUND_ERROR = 'NOT_FOUND_ERROR',
  CONFLICT_ERROR = 'CONFLICT_ERROR',
  INTERNAL_ERROR = 'INTERNAL_ERROR',
  QUERY_ERROR = 'QUERY_ERROR',
  STATS_ERROR = 'STATS_ERROR',
  HTTP_ERROR = 'HTTP_ERROR',
  INVALID_PARAMETER = 'INVALID_PARAMETER',
  RATE_LIMIT_ERROR = 'RATE_LIMIT_ERROR',
  ACCOUNT_LOCKED_ERROR = 'ACCOUNT_LOCKED_ERROR',
  EXTERNAL_SERVICE_ERROR = 'EXTERNAL_SERVICE_ERROR',
  BUSINESS_ERROR = 'BUSINESS_ERROR',
  RELATION_EXISTS = 'RELATION_EXISTS',
  ALL_VERSIONS_HAVE_RELATIONS = 'ALL_VERSIONS_HAVE_RELATIONS'
}

// 错误详情接口
export interface ErrorDetail {
  type: ErrorType;
  message: string;
  field?: string;
  code?: string;
  details?: Record<string, any>;
}

// 分页信息接口 - 与后端 app/core/response.py 的 Pagination 模型对齐
export interface Pagination {
  total: number;
  page: number;
  size: number;
  pages: number;
  has_prev: boolean;
  has_next: boolean;
}

// 基础API响应接口 - 与后端 app/core/response.py 的 ApiResponse 模型对齐
export interface ApiResponse<T = any> {
  pagination?: any;
  status: number;
  statusText: string;
  success: boolean;
  code: number;
  message: string;
  data?: T;
  error?: ErrorDetail;
  timestamp: string;
  request_id?: string;
}

// 分页响应接口 - 与后端 paginated_response 函数返回格式对齐
export interface PaginatedResponse<T = any> {
  success: boolean;
  code: number;
  message: string;
  data: T[];
  pagination: Pagination;
  error?: ErrorDetail;
  timestamp: string;
  request_id?: string;
}

// 常用的响应类型别名
export type SuccessResponse<T> = ApiResponse<T> & { success: true; data: T };
export type ErrorResponse = ApiResponse<null> & { success: false; error: ErrorDetail };

// 业务错误类，用于前端错误处理
export class BusinessError extends Error {
  public readonly type: ErrorType;
  public readonly field?: string;
  public readonly code?: string;
  public readonly requestId?: string;
  public readonly details?: Record<string, any>;

  constructor(error: ErrorDetail, requestId?: string) {
    super(error.message);
    this.name = 'BusinessError';
    this.type = error.type;
    this.field = error.field;
    this.code = error.code;
    this.requestId = requestId;
    this.details = error.details;
  }

  // 判断是否为特定类型的错误
  isType(type: ErrorType): boolean {
    return this.type === type;
  }

  // 判断是否为验证错误
  isValidationError(): boolean {
    return this.type === ErrorType.VALIDATION_ERROR;
  }

  // 判断是否为认证错误
  isAuthenticationError(): boolean {
    return this.type === ErrorType.AUTHENTICATION_ERROR;
  }

  // 判断是否为授权错误
  isPermissionError(): boolean {
    return this.type === ErrorType.PERMISSION_ERROR;
  }

  // 判断是否为资源不存在错误
  isNotFoundError(): boolean {
    return this.type === ErrorType.NOT_FOUND_ERROR;
  }

  // 判断是否为冲突错误
  isConflictError(): boolean {
    return this.type === ErrorType.CONFLICT_ERROR;
  }

  // 判断是否为内部服务器错误
  isInternalError(): boolean {
    return this.type === ErrorType.INTERNAL_ERROR;
  }
}

// API响应处理工具函数
export class ApiResponseHandler {
  // 检查响应是否成功
  static isSuccess<T>(response: ApiResponse<T>): response is SuccessResponse<T> {
    return response.success === true && response.data !== undefined;
  }

  // 检查响应是否失败
  static isError(response: ApiResponse<any>): response is ErrorResponse {
    return response.success === false && response.error !== undefined;
  }

  // 从响应中提取数据，失败时抛出BusinessError
  static extractData<T>(response: ApiResponse<T>): T {
    if (this.isSuccess(response)) {
      return response.data;
    }
    
    if (this.isError(response)) {
      throw new BusinessError(response.error, response.request_id);
    }
    
    throw new Error('Invalid API response format');
  }

  // 从分页响应中提取数据
  static extractPaginatedData<T>(response: PaginatedResponse<T>): { data: T[]; pagination: Pagination } {
    if (response.success && response.data && response.pagination) {
      return {
        data: response.data,
        pagination: response.pagination
      };
    }
    
    if (response.success === false && response.error) {
      throw new BusinessError(response.error, response.request_id);
    }
    
    throw new Error('Invalid paginated API response format');
  }

  // 安全地获取数据，失败时返回默认值
  static safeExtractData<T>(response: ApiResponse<T>, defaultValue: T): T {
    try {
      return this.extractData(response);
    } catch {
      return defaultValue;
    }
  }

  // 获取错误信息
  static getErrorMessage(response: ApiResponse<any>): string {
    if (this.isError(response)) {
      return response.error.message;
    }
    return response.message || 'Unknown error';
  }
}

// 常用错误消息常量 - 与后端 ErrorMessages 保持一致
export const ErrorMessages = {
  NETWORK_ERROR: '网络连接失败，请检查网络设置',
  TIMEOUT_ERROR: '请求超时，请稍后重试',
  UNKNOWN_ERROR: '未知错误，请联系管理员',
  OPERATION_FAILED: '操作失败',
  VALIDATION_FAILED: '参数验证失败',
  AUTHENTICATION_FAILED: '认证失败',
  PERMISSION_DENIED: '权限不足',
  NOT_FOUND: '资源不存在',
  CONFLICT: '资源冲突',
  INTERNAL_ERROR: '服务器内部错误',
  QUERY_FAILED: '查询失败',
  CREATE_FAILED: '创建失败',
  UPDATE_FAILED: '更新失败',
  DELETE_FAILED: '删除失败',
  UNAUTHORIZED: '未授权访问，请先登录',
  FORBIDDEN: '权限不足，无法访问',
  INTERNAL_SERVER_ERROR: '服务器内部错误，请稍后重试'
} as const;

// HTTP状态码映射到错误类型 - 与后端错误处理保持一致
export const HttpStatusToErrorType: Record<number, ErrorType> = {
  400: ErrorType.VALIDATION_ERROR,
  401: ErrorType.AUTHENTICATION_ERROR,
  403: ErrorType.PERMISSION_ERROR,
  404: ErrorType.NOT_FOUND_ERROR,
  409: ErrorType.CONFLICT_ERROR,
  422: ErrorType.VALIDATION_ERROR,
  429: ErrorType.RATE_LIMIT_ERROR,
  500: ErrorType.INTERNAL_ERROR,
  502: ErrorType.EXTERNAL_SERVICE_ERROR,
  503: ErrorType.EXTERNAL_SERVICE_ERROR,
  504: ErrorType.EXTERNAL_SERVICE_ERROR
};